package com.wondream.myframework.app.common.util;

import java.util.Random;

/**
 * 系统工具类
 */
public class GmidSystemUtils {
    public static final int[] EMPTY_INT_ARRAY = new int[0];

    public static final String OS_NAME_WINDOWS_PREFIX = "Windows";

    public static final Random RANDOM = new Random();

    public static final boolean IS_OS_WINDOWS = getOsMatchesName(OS_NAME_WINDOWS_PREFIX);

    public static long nextLong(final long startInclusive, final long endExclusive) {
        isTrue(endExclusive >= startInclusive, "startInclusive must be smaller or equals to endExclusive");
        isTrue(startInclusive >= 0, "startInclusive must be non-negative");
        if (startInclusive == endExclusive) {
            return startInclusive;
        }
        double result = nextDouble(startInclusive, endExclusive);
        return (long) result;
    }

    private static double nextDouble(long startInclusive, long endExclusive) {
        isTrue(endExclusive >= startInclusive, "startInclusive must be smaller or equals to endExclusive");
        isTrue(startInclusive >= 0, "startInclusive must be non-negative");
        if (startInclusive == endExclusive) {
            return startInclusive;
        }
        return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextDouble());
    }

    private static void isTrue(final boolean expression, String message, Object... values) {
        if (!expression) {
            throw new IllegalArgumentException(String.format(message, values));
        }
    }

    public static int[] toCodePoints(final CharSequence str){
        if(str == null){
            return null;
        }
        if(str.length() == 0){
            return EMPTY_INT_ARRAY;
        }
        final String s = str.toString();
        int[] result = new int[s.codePointCount(0, s.length())];
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            result[i] = s.codePointAt(index);
            index += Character.charCount(result[i]);
        }
        return result;
    }

    public static String getHostName(){
        return IS_OS_WINDOWS ? System.getenv("COMPUTERNAME") : System.getenv("HOSTNAME");
    }


    private static boolean getOsMatchesName(final String osNamePrefix) {
        return isOSNameMatch(getSystemProperty("os.name"), osNamePrefix);
    }

    private static boolean isOSNameMatch(final String osName, String osNamePrefix) {
        if(osName == null){
            return false;
        }
        return osName.startsWith(osNamePrefix);
    }

    private static String getSystemProperty(final String property) {
        try {
            return System.getProperty(property);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
